package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.dao.KwWxSubscribeDao;
import com.meirengu.webview.model.KwWxSubscribe;
import com.meirengu.webview.service.KwOperationLogService;
import com.meirengu.webview.service.KwWxSubscribeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * KwWxSubscribe服务实现层
 *
 * @author Liu
 * @create Fri Oct 19 10:41:02 CST 2018
 */
@Service
public class KwWxSubscribeServiceImpl extends BaseServiceImpl<KwWxSubscribe> implements KwWxSubscribeService {


    @Autowired
    RedisClient redisClient;

    @Autowired
    ProducerBean producer;

    @Autowired
    private KwWxSubscribeDao kwWxSubscribeDao;

    @Autowired
    private KwOperationLogService kwOperationLogService;


    Logger logger = LoggerFactory.getLogger(KwWxSubscribeServiceImpl.class);


    public void wxAccessTokenByAccount(String account) throws Exception {
        String accessToken = "";
        String appid = "";
        String secret = "";
        /**测试公众号*/
        if ("gh_2c93a53f530a".equals(account)) {
            appid = "wx21a75341b397580a";
            secret = "7fcd4786fd125d522a8a98cb4cf1e1cb";
        }

        HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
        int code = hr.getStatusCode();
        if (code == 200) {
            logger.info("==wxAccessToken http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            accessToken = returnMsg.getString("access_token");
            redisClient.set("WXACCESSTOKEN" + account, accessToken);
        } else {
            logger.warn("==wxAccessToken http requesst fail. code:{}, result:{}", code, hr.toString());
        }


    }

    public void wxAccessToken() throws Exception {
        String accessToken = "";
        /*HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c09d7bf83d9b8f2&secret=3c6667228c17dd595f69dfb45d098d2b");*/
        HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7ba900a76b392240&secret=6c557ce4f8bbec5b6135c6958030ad20");
        int code = hr.getStatusCode();
        if (code == 200) {
            logger.info("==wxAccessToken http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            accessToken = returnMsg.getString("access_token");
            redisClient.set("WXACCESSTOKEN", accessToken);
        } else {
            logger.warn("==wxAccessToken http requesst fail. code:{}, result:{}", code, hr.toString());
        }


    }


    public void createMenu() throws Exception {
        /*JSONObject jsonObject = new JSONObject();
        JSONArray button = new JSONArray();
        JSONObject button1 = new JSONObject();//我要贷款
        JSONObject button2 = new JSONObject();//帮你借
        JSONObject button3 = new JSONObject();//大额借款

        button1.put("type", "view");
        button1.put("name", "⚡秒下款");
        button1.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg#/market");
        button.add(button1);

        button2.put("type","click");
        button2.put("name","\uD83D\uDCB0帮你借");
        button2.put("key","CLICK_HELP_LOAN");
        button.add(button2);

        button3.put("type", "view");
        button3.put("name", "\uD83D\uDD25大额借款");
        button3.put("url", "https://mdzj139.com/loan/?cid=channel_wxtg");
        button.add(button3);
        jsonObject.put("button", button);*/
        JSONObject jsonObject = new JSONObject();
        JSONArray button = new JSONArray();
        JSONObject button1 = new JSONObject();//小额借款
        JSONObject button2 = new JSONObject();//大额借款

        button1.put("type", "view");
        button1.put("name", "小额借款");
        button1.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg#/market");
        button.add(button1);

        button2.put("type", "view");
        button2.put("name", "大额借款");
        button2.put("url", "https://mdzj139.com/loan/?cid=channel_wxtg");
        button.add(button2);
        jsonObject.put("button", button);

        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + redisClient.get("WXACCESSTOKEN");
        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
        System.out.println(hr.toString());
    }

    public void getUserList() throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + redisClient.get("WXACCESSTOKEN");
        /*String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=14_XtlAFIKufRItmgnngj9qi00aSvVEgANRktePBLaPct5jQ0okZpNY4IvZN5AQ1LqasQAeITrFAbKOp4upvySBq7KMbz8ETIhAOovNTY4YLPfSn3UWYkPR6cmXkbD822v0fnSuWsGQzt5nrO9aTSNbAEALKF";*/
        HttpUtil.HttpResult hr = HttpUtil.doGet(url);
        int code = hr.getStatusCode();
        if (code == 200) {
            logger.info("==getUserList http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            JSONObject data = returnMsg.getJSONObject("data");
            JSONArray openidAry = data.getJSONArray("openid");
            String toUserName = "gh_895ae09a34b3";
            String openid = null;
            //校验是否已订阅
            Map<String, Object> params = new HashMap<>();
            Integer count = null;
            KwWxSubscribe kwWxSubscribe = null;
            for (int i = 0; i < openidAry.size(); i++) {
                openid = openidAry.getString(i);
                params.put("fromUserName", openid);
                params.put("toUserName", toUserName);
                count = getCount(params);
                //已有推送记录
                if (!NumberUtil.isNullOrZero(count)) {
                    System.out.println("已有订阅");
                    continue;
                }
                kwWxSubscribe = new KwWxSubscribe();
                String userUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + redisClient.get("WXACCESSTOKEN") + "&openid=" + openid + "&lang=zh_CN";
                HttpUtil.HttpResult hr1 = HttpUtil.doGet(userUrl);
                String content1 = new String(hr1.getContent().getBytes("ISO-8859-1"), "UTF-8");
                logger.info("content1:{}" + content1);
                JSONObject jsonObject = JSONObject.parseObject(content1);
                String nikeName = jsonObject.getString("nickname");
                kwWxSubscribe.setToUserName(toUserName);
                kwWxSubscribe.setFromUserName(openid);
                kwWxSubscribe.setCreateTime(new Date());
                kwWxSubscribe.setMsgType("event");
                kwWxSubscribe.setEvent("subscribe");
                kwWxSubscribe.setNikeName(nikeName);
                insert(kwWxSubscribe);
            }

        } else {
            logger.warn("==wxAccessToken http requesst fail. code:{}, result:{}", code, hr.toString());
        }
    }


    public void sendTemplateMsg(String name) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> map = new HashMap<>();
        map.put("toUserName", "gh_895ae09a34b3");
        List<Map<String, Object>> userList = getList(map);
        String openid = null;
        JSONObject dataJson = null;
        JSONObject first = null;
        JSONObject keyword1 = null;
        JSONObject keyword2 = null;
        JSONObject keyword3 = null;
        JSONObject keyword4 = null;
        JSONObject keyword5 = null;
        JSONObject remark = null;
        kwOperationLogService.addOperationLog("2", "sendTemplateMsg", "发送花花有钱模板消息",
                name, sdf.format(new Date()), sdf.format(new Date()), "sendTemplateMsg", 0,
                null, null, null);
        for (Map<String, Object> userMap : userList) {
            openid = userMap.get("fromUserName").toString();
            jsonObject.put("touser", openid);
            jsonObject.put("template_id", "jEXmeKGIEI7v_XNceioEXv1H9HOTfE6SHTGVtq8UvqA");
            jsonObject.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg#/market");
            dataJson = new JSONObject();

            first = new JSONObject();
            first.put("value", "根据您的资质和情况，已符合贷款资格，额度1000-5000元");
            first.put("color", "#FF0000");
            dataJson.put("first", first);

            keyword1 = new JSONObject();
            keyword1.put("value", name);
            keyword1.put("color", "#173177");
            dataJson.put("keyword1", keyword1);

            keyword2 = new JSONObject();
            keyword2.put("value", "1000-5000元");
            keyword2.put("color", "#173177");
            dataJson.put("keyword2", keyword2);

            keyword3 = new JSONObject();
            keyword3.put("value", "7-30天");
            keyword3.put("color", "#173177");
            dataJson.put("keyword3", keyword3);


            remark = new JSONObject();
            StringBuilder contentBuffer = new StringBuilder();
            contentBuffer.append("点击立即申请>>>");
            String contentStr = contentBuffer.toString();
            remark.put("value", contentStr);
            remark.put("color", "#FF0000");
            dataJson.put("remark", remark);

            jsonObject.put("data", dataJson);

            /*String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=14_DhgdYNoEVjs2ajDbFpyrDF9V-Xaaq9GLd_iGYgocAWs_LyCMw0fDnjmV5ItLcrhUlnNnRqjoPZVdqH3w2QA4pa2mumB9gFuE_GnHifgXm_qPO7iCBwc4gPqtRCsHGRx4vIFL4oHUAzT-bS0FMVOfADAVEX";*/
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisClient.get("WXACCESSTOKEN");
            HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
            System.out.println(hr.toString());
        }


    }

    public void sendTemplateMsgMultiple(String name) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Object> map = new HashMap<>();
        map.put("toUserName", "gh_895ae09a34b3");
        List<Map<String, Object>> userList = getList(map);
        Executor executor = Executors.newFixedThreadPool(30);//启用多线程
        for (Map<String, Object> userMap : userList) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String openid = null;
                        JSONObject jsonObject = new JSONObject();
                        JSONObject dataJson = null;
                        JSONObject first = null;
                        JSONObject keyword1 = null;
                        JSONObject keyword2 = null;
                        JSONObject keyword3 = null;
                        JSONObject keyword4 = null;
                        JSONObject keyword5 = null;
                        JSONObject remark = null;
                        openid = userMap.get("fromUserName").toString();
                        jsonObject.put("touser", openid);
                        jsonObject.put("template_id", "jEXmeKGIEI7v_XNceioEXv1H9HOTfE6SHTGVtq8UvqA");
                        jsonObject.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg#/market");
                        dataJson = new JSONObject();

                        first = new JSONObject();
                        first.put("value", "根据您的资质和情况，已符合贷款资格，额度1000-5000元");
                        first.put("color", "#FF0000");
                        dataJson.put("first", first);

                        keyword1 = new JSONObject();
                        keyword1.put("value", name);
                        keyword1.put("color", "#173177");
                        dataJson.put("keyword1", keyword1);

                        keyword2 = new JSONObject();
                        keyword2.put("value", "1000-5000元");
                        keyword2.put("color", "#173177");
                        dataJson.put("keyword2", keyword2);

                        keyword3 = new JSONObject();
                        keyword3.put("value", "7-30天");
                        keyword3.put("color", "#173177");
                        dataJson.put("keyword3", keyword3);


                        remark = new JSONObject();
                        StringBuilder contentBuffer = new StringBuilder();
                        contentBuffer.append("点击立即申请>>>");
                        String contentStr = contentBuffer.toString();
                        remark.put("value", contentStr);
                        remark.put("color", "#FF0000");
                        dataJson.put("remark", remark);

                        jsonObject.put("data", dataJson);

                        /*String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=14_DhgdYNoEVjs2ajDbFpyrDF9V-Xaaq9GLd_iGYgocAWs_LyCMw0fDnjmV5ItLcrhUlnNnRqjoPZVdqH3w2QA4pa2mumB9gFuE_GnHifgXm_qPO7iCBwc4gPqtRCsHGRx4vIFL4oHUAzT-bS0FMVOfADAVEX";*/
                        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisClient.get("WXACCESSTOKEN");
                        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
                        System.out.println(hr.toString());
                    } catch (Exception e) {
                    }
                }
            });

        }

    }


    @Override
    public List<KwWxSubscribe> getModel(Map map) {
        return kwWxSubscribeDao.getModel(map);
    }


}
